
package com.qst.itoffer.controller;

import com.qst.itoffer.entity.PageBean;
import com.qst.itoffer.entity.User;
import com.qst.itoffer.listener.OnlineUsersListener;
import com.qst.itoffer.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping
public class UserController {
    @Autowired
    private  UserService userService;
    @Autowired
    private OnlineUsersListener onlineUsersListener;
    @GetMapping("/login")
    public String loginPage(@RequestParam(required = false) Integer error, Model model) {
        if(error != null) {
            model.addAttribute("error", error);
        }
        return "/manage/login.html";
    }
    @PostMapping("/login")
    public String login(
            @RequestParam String userLogname,
            @RequestParam String userPwd,
            @RequestParam String validateCode,
            HttpServletRequest request, RedirectAttributes redirectAttributes) {

        //验证码验证
        HttpSession session = request.getSession();
        String sessionCode = (String) session.getAttribute("validateCode");
        log.info("sessionCode: " + sessionCode);

        if (sessionCode == null || !sessionCode.equalsIgnoreCase(validateCode)) {
            redirectAttributes.addFlashAttribute("error", "验证码错误");
            log.info("验证码错误");
            return "redirect:/login";
        }
        User user = userService.login(userLogname, userPwd);
        if (user == null) {
            redirectAttributes.addFlashAttribute("error", "用户名或密码错误");
            log.info("用户名或密码错误");
            return "redirect:/login";
        }

        session.setAttribute("user", user);
        log.info("用户登录成功：" + user.getUserLogname());
        return "redirect:/manage/main.html"; // 关键点：强制重定向

    }
    @PostMapping("/UserAddServlet123")
    public String addUser(@ModelAttribute User user) {
        userService.saveUser(user);
        System.out.println("用户添加成功！");
        return "redirect:/userslist";
    }
    //用户退出登录
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        // 1. 从Session中获取当前用户
        User user = (User) session.getAttribute("user");
        if (user != null) {
            // 2. 更新用户状态为离线（可选）
            userService.updateUserStatus(user.getUserId(), 0);//多余了，数据库没有status这一属性哈哈哈哈哈....
            log.info("用户退出登录：" + user.getUserLogname());
            // 3. 使Session失效
            session.invalidate();
        }

        // 4. 重定向到登录页
        return "redirect:/login.html";
    }
    //展示用户

    @GetMapping("/userslist")
    public String list(@RequestParam(defaultValue = "1") int pageNo, Model model) {
        int pageSize = 10;
        PageBean<User> pageBean = userService.getUsersByPage(pageNo, pageSize);
        model.addAttribute("pageBean", pageBean);
        //用户动态展示
        List<User> userList = userService.getAllUsers();
        log.info("用户列表：" + userList);
        model.addAttribute("users",  userList);
        return "manage/userList";
    }
    //删除用户
    @GetMapping("/userDelete")
    public String delete(@RequestParam("userId") Integer userId) {
        userService.deleteUser(userId);
        log.info("用户删除：" + userId);
        return "redirect:/userslist";
    }

    @GetMapping("/updateSelect")
    public String updateSelect(@RequestParam("userId") Integer userId, Model model) {
        model.addAttribute("user", userService.getUserById(userId));
        log.info("用户更新：" + userId);
        return "/manage/userUpdate";
    }

    @PostMapping("/update")
    public String update(User user) {
        userService.updateUser(user);
        log.info("用户更新数据"+  user);
        log.info("用户更新成功：" + user.getUserLogname());
        return "redirect:/userslist";
    }
    //监听用户在线

    @GetMapping("/userOnline")
    public String userOnline(Model model) {
        Map<String, Object> onlineUsers = onlineUsersListener.getOnlineUsers();
        model.addAttribute("onlineUsers", onlineUsers);
        return "/manage/userOnline";
    }


}
